package com.fu.esdemo.service.impl;

import cn.hutool.json.JSONUtil;
import com.fu.esdemo.bean.DocBean;
import com.fu.esdemo.dao.ElasticRepository;
import com.fu.esdemo.service.IElasticService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service("elasticService")
public class ElasticServiceImpl implements IElasticService
{
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
 
    @Autowired
    private ElasticRepository elasticRepository;

    @Autowired
    private RestHighLevelClient client;
 
    private Pageable pageable = PageRequest.of(0, 10);

    @Override
    public void insertIndex() throws Exception {
        DocBean docBean = new DocBean();
        docBean.setContent("张三");
        docBean.setId(111L);
        docBean.setFirstCode("zhang");
        docBean.setSecordCode("san");
        docBean.setType(1);

        IndexRequest request = new IndexRequest("ems");
        request.source(JSONUtil.toJsonStr(docBean), XContentType.JSON);

        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

        System.out.println(indexResponse.status());
        System.out.println(indexResponse.toString());
    }

    @Override
    public void searchIndex() throws Exception {
        SearchRequest searchRequest = new SearchRequest("ems");
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        QueryBuilder qb = new MatchQueryBuilder("content", "苹果");
        ssb.query(qb);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("content");

        ssb.highlighter(highlightBuilder);

        searchRequest.source(ssb);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String record = hit.getSourceAsString();
            System.out.println(record);

            HighlightField highlightField = hit.getHighlightFields().get("content");
            for (Text fragment : highlightField.getFragments()) {
                System.out.println(fragment.string());
            }

        }
    }

    @Override
    public void searchSuggest(String prefix) throws Exception {
        SearchRequest searchRequest = new SearchRequest("my_suggester");
        SearchSourceBuilder ssb = new SearchSourceBuilder();

        CompletionSuggestionBuilder suggest = SuggestBuilders
                .completionSuggestion("suggest")
                .prefix(prefix);

        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("s-test2",suggest);

        ssb.suggest(suggestBuilder);

        searchRequest.source(ssb);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        CompletionSuggestion suggestion = response.getSuggest().getSuggestion("s-test2");
        for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
            System.out.println(option.getText().string());
        }
    }

    @Override
    public void createIndex()
    {
        elasticsearchTemplate.createIndex(DocBean.class);
    }

    @Override
    public void searchAggregation() throws Exception {
        SearchRequest searchRequest = new SearchRequest("ems");
        SearchSourceBuilder ssb = new SearchSourceBuilder();

        TermsAggregationBuilder category = AggregationBuilders.terms("content").field("content.keyword");
        ssb.aggregation(category);

        searchRequest.source(ssb);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        Terms terms = response.getAggregations().get("content");

        for (Terms.Bucket bucket : terms.getBuckets()) {
            System.out.println(bucket.getKey());
            System.out.println(bucket.getDocCount());
        }
    }

    @Override
    public void deleteIndex(String index)
    {
        elasticsearchTemplate.deleteIndex(index);
    }
 
    @Override
    public void save(DocBean docBean)
    {
        elasticRepository.save(docBean);
    }
 
    @Override
    public void saveAll(List<DocBean> list)
    {
        elasticRepository.saveAll(list);
    }

    @Override
    public Iterator<DocBean> findAll()
    {
        return elasticRepository.findAll().iterator();
    }
 
    @Override
    public Page<DocBean> findByContent(String content)
    {
        // TODO Auto-generated method stub
        return null;
    }
 
    @Override
    public Page<DocBean> findByFirstCode(String firstCode)
    {
        // TODO Auto-generated method stub
         return elasticRepository.findByContent(firstCode,pageable);
    }
 
    @Override
    public Page<DocBean> findBySecordCode(String secordCode)
    {
        // TODO Auto-generated method stub
        return elasticRepository.findBySecordCode(secordCode, pageable);
    }
 
    @Override
    public Page<DocBean> query(String key)
    {
        // TODO Auto-generated method stub
        return elasticRepository.findByContent(key, pageable);
    }
 
   
 
}